package jxau.jwgl;

import jxau.jwgl.api.WebApiFactory;
import jxau.jwgl.task.TaskExecutor;
import jxau.jwgl.task.TaskExecutorImpl;
import jxau.jwgl.utils.net.OkHttpBuilder;
import jxau.jwgl.web.utils.BasePathFreeMarkerView;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import retrofit2.Retrofit;

/**
 * JwglConfiguration
 *
 * @author LongShu 2017/06/04
 */
@Configuration
@ComponentScan("jxau.jwgl")
@EnableCaching
public class JwglConfiguration {

    public static Boolean devMode = Boolean.FALSE;

    public JwglConfiguration() {
        config();
    }

    @Bean
    public TaskExecutor taskExecutor() {
        TaskExecutor taskExecutor = new TaskExecutorImpl();
        return taskExecutor;
    }

    @Bean
    public FreeMarkerViewResolver getFreeMarkerViewResolver() {
        FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
        viewResolver.setCache(!devMode);
        viewResolver.setSuffix(".html");
        viewResolver.setContentType("text/html; charset=utf-8");
        viewResolver.setExposeRequestAttributes(true);
        // viewResolver.setExposeSessionAttributes(true);
        viewResolver.setRequestContextAttribute("request");
        viewResolver.setViewClass(BasePathFreeMarkerView.class);
        return viewResolver;
    }

    /*@Bean
    public FreeMarkerConfigurer getFreeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();

        configurer.setDefaultEncoding("UTF-8");
        configurer.setTemplateLoaderPath("classpath:/templates/");
        Properties freemarkerSettings = new Properties();
        try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("freemarker.properties");) {
            freemarkerSettings.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        configurer.setFreemarkerSettings(freemarkerSettings);

        return configurer;
    }*/

    @Bean
    public Retrofit retrofit() {
        return WebApiFactory.getBuilder().build();
    }

    /**
     * 其他配置
     */
    static void config() {
        // OkHttp
        if (devMode) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            OkHttpBuilder.addGlobalInterceptor(loggingInterceptor);
        }
    }

}
